<script>
//electron modules
const { exec, execFile } = window.require("child_process");
const fs = window.require("fs");
//app
import xml2js from 'xml2js';
import { dateObject2timeStr } from "../util/util-datetime";
import colors from '../util/colors';

export default {
    data() {
        return {
            stat: false,  //是否在运行
            text: "",
            panelName: "Tomcat",
            colors: colors
        };
    },
    mounted() {
        this.checkPortOnce(flag => {
            if (flag) {
                this.watchLog();
            }
            this.checkPort();
        });
    },
    destroyed() {
        clearInterval(this.itv);
    },
    methods: {
        changeStat(flag) {
            this.stat = flag;
        },
        getTomcatPort() {
            return new Promise(resolve => {
                const configFile = `tomcat/conf/server.xml`;
                console.log("Tomcat configFile", configFile);
                const xml = fs.readFileSync(configFile, "utf-8");
                const parser = new xml2js.Parser();
                parser.parseString(xml, (err, result) => {
                    if (err) throw err;
                    const connector = result.Server.Service[0].Connector;
                    const connectorWithPort = connector.find(obj => obj.$.protocol == 'HTTP/1.1');
                    resolve(connectorWithPort.$.port);
                });
            });
        },
        async checkPort() {
            const port = await this.getTomcatPort();
            this.itv = setInterval(() => {
                exec(`netstat -ano|findstr \":${port}\"`, (err, stdout, stderr) => {
                    if (err) {
                        this.changeStat(false);
                    } else {
                        if (stdout.indexOf("LISTENING") >= 0) {
                            this.changeStat(true);
                        } else {
                            this.changeStat(false);
                        }
                    }
                })
            }, 1000);
        },
        async checkPortOnce(callback) {
            const port = await this.getTomcatPort();
            exec(`netstat -ano|findstr \":${port}\"`, (err, stdout, stderr) => {
                if (err) {
                    this.changeStat(false);
                    if (callback) callback(false);
                } else {
                    if (stdout.indexOf("LISTENING") >= 0) {
                        this.changeStat(true);
                        if (callback) callback(true);
                    } else {
                        this.changeStat(false);
                        if (callback) callback(false);
                    }
                }
            });
        },
        start() {
            if (this.stat) {
                alert(`${this.panelName}正在运行`);
            } else {
                this.text = "启动中，根据项目情况，可能需要较多的时间，请耐心等待...";
                exec("startup.bat", {
                    cwd: "tomcat"
                }, (err, stdout, stderr) => {
                    if (err) throw err;
                });
                this.watchLog();
            }
        },
        watchLog() {
            exec(`taskkill /f /t /im tail.exe`, {
                cwd: "./"
            }, (err, stdout, stderr) => {
                if (err) console.log("tail 已经终止");

                console.log('启动日志监控');
                const nowDate = dateObject2timeStr(new Date(), "yyyy-MM-dd");
                const logFile = `tomcat/logs/catalina.${nowDate}.log`;
                const build = exec(`tail.bat ${logFile}`, {
                    cwd: "./utils"
                }, (err, stdout, stderr) => {
                    if (err) console.log('日志监控被终止');
                });
                build.stdout.on('data', data => {
                    console.log(data);
                    this.text = data;
                    this.$refs.textarea.scrollTop = this.$refs.textarea.scrollHeight;
                });
            });
        },
        shutdown() {
            if (this.stat) {
                exec("shutdown.bat", {
                    cwd: "tomcat"
                }, (err, stdout, stderr) => {
                    if (err) throw err;
                });
            } else {
                alert(`${this.panelName}已经关闭`);
            }

        }

    }

}
</script>

<template>
    <div class="container">
        <div class="title">{{panelName}}管理</div>
        <div class="flexContainer">
            <button class="startup" @click="start()">启动{{panelName}}</button>
            <button class="startup" :style="{backgroundColor: colors.red }" @click="shutdown()"> 关闭{{panelName}}
            </button>
            <div>
                <span v-if="stat" :style="{ verticalAlign: 'middle', color: 'green', fontSize: '14px' }">启动中</span>
                <span v-if="!stat" :style="{ verticalAlign: 'middle', color: colors.red, fontSize: '14px' }">未启动</span>
                &nbsp;
                <div v-if="stat" class="stat" :style="{backgroundColor:'green'}"></div>
                <div v-if="!stat" class="stat" :style="{backgroundColor:colors.red}"></div>
            </div>
        </div>
        <textarea readonly ref="textarea" v-model="text"></textarea>
    
    </div>
</template>


<style scoped>
.container {
    border: 1px solid #eee;
    margin: 10px;
    position: relative
}

.title {
    position: absolute;
    top: 0;
    text-align: left;
    left: 10px;
    top: -10px;
    height: 20px;
    line-height: 20px;
    font-size: 12px;
    background-color: #fff;
    color: #aaa;
}

.flexContainer {
    display: flex;
    flex-flow: row nowrap;
    justify-content: space-around;
    align-items: center;
    height: 100px;
}

.startup {
    text-align: center;
    background-color: green;
    padding: 15px 40px;
    color: #fff;
    display: block;
    font-size: 14px;
}

.stat {
    height: 10px;
    width: 10px;
    display: inline-block;
    vertical-align: middle;
}

textarea {
    height: 200px;
    width: 100%;
    font-size: 12px;
    outline: none;
    resize: none;
}
</style>
